import os
import re
# import PyPDF2

# 如果需要更好的文本提取，可以使用 pdfplumber 替代 PyPDF2
import pdfplumber

def pdf_to_text(pdf_path):
    """将 PDF 文件转换为文本"""
    try:
        with pdfplumber.open(pdf_path) as pdf:
            text = ""
            for page in pdf.pages:
                text += page.extract_text()
                # text = text.replace("\n", " ")
            return text
    except Exception as e:
        print(f"无法处理文件 {pdf_path}: {e}")
        return None

def batch_convert_pdf_to_txt(directory):
    """批量将指定目录中的所有 PDF 转换为 TXT 文件"""
    # 创建输出文件夹
    output_dir = os.path.join(directory, "txt_files")
    os.makedirs(output_dir, exist_ok=True)

    # 遍历目录中的所有 PDF 文件
    for filename in os.listdir(directory):
        if filename.lower().endswith(".pdf"):
            pdf_path = os.path.join(directory, filename)
            text = pdf_to_text(pdf_path)

            if text:
                # 将转换后的文本保存为 TXT 文件
                txt_filename = f"{os.path.splitext(filename)[0]}.txt"
                txt_path = os.path.join(output_dir, txt_filename)

                with open(txt_path, "w", encoding="utf-8") as txt_file:
                    txt_file.write(text)
                print(f"成功将 {filename} 转换为 {txt_filename}")
            else:
                print(f"跳过文件 {filename}，转换失败。")

if __name__ == "__main__":
    directory = input("请输入要处理的目录路径：")
    batch_convert_pdf_to_txt(directory)
